#include "stdafx.h"
#include "UpgraApp.h"

#include "TempFile.h"
#include "Setup.h"

UpgraApp*	UpgraApp::app;

void UpgraApp::begin(PTSTR cmdLine){
	app=new UpgraApp();
	app->thread=CreateThread(NULL,0,threadProc,app,0,0);
	app->cmdLine=cmdLine;
}
void UpgraApp::end(void){
	if(app && app->bin)
		WaitForSingleObject(app->thread,30000);
	delete app;
}
void UpgraApp::exec(void){
	HttpFx* h=new HttpFx(0,0);
	try{
		bin=h->get(L"/xync/upgrade",0,0);//HttpFx::get(L"/xync/upgrade",0,0);
		if(bin->getLength()){
			TempFile *t=new TempFile();
			t->write(bin);
			t->exec(cmdLine);
			delete t;
		}
	}catch(int){
	}
	if(bin){
		delete bin;
		bin=0;
	}
}
void UpgraApp::setup(PTSTR appName,uint message,PTSTR noupgrade){
	HWND h;
	while(h=FindWindow(appName,0)){
		SendMessage(h,message,0x55aa55aa,0xaa55aa55);
		Sleep(1000);
	}
	Setup::copy(appName);
	Setup::exec(noupgrade);
}
uint WINAPI UpgraApp::threadProc(void *param){
	((UpgraApp*)param)->exec();
	return 0;
}